package com.sjb.sixteen_journey_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.entity.ChatList;
import com.sjb.sixteen_journey_backend.mapper.ChatListMapper;
import com.sjb.sixteen_journey_backend.service.IChatListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.sixteen_journey_backend.service.IUserService;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 私聊表 服务实现类
 * </p>
 *
 * @author jcz
 * @since 2024-08-17
 */
@Service
public class ChatListServiceImpl extends ServiceImpl<ChatListMapper, ChatList> implements IChatListService {

    @Autowired
    private ChatListMapper chatListMapper;

    @Autowired
    private IUserService userService;
    @Override
    public R addChatList(ChatList chatList) {
        boolean save = this.save(chatList);
        if (save)
            return R.success(null,"添加成功");
        return R.error("添加失败");
    }

    @Override
    public R<List<ChatList>> chatSingle(Integer fromId, Integer toId) {
        try {
            if(userService.getUserById(toId)==null) return R.error("接收用户不存在");
            QueryWrapper<ChatList> wrapper = Wrappers.query();
            wrapper.and(w ->
                    w.eq("from_user_id", fromId).eq("to_user_id", toId)
                    .or().eq("from_user_id", toId).eq("to_user_id", fromId));
            List<ChatList> list = this.list(wrapper);
            if(list.size()<0) return R.error("没有数据");
            else return R.success(list,"查询成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public R<List<Map<String, Object>>> getCountByFromUserId() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer fromUserId = (Integer) map.get("id");
            QueryWrapper<ChatList> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("to_user_id", "count(*) as count")
                    .eq("from_user_id", fromUserId)
                    .eq("is_Looked", 1)
                    .groupBy("to_user_id");
            List<Map<String, Object>> maps = chatListMapper.selectMaps(queryWrapper);
            if (maps.size() > 0) {
                return R.success(maps, "查询成功");
            } else {
                return R.error("没有数据");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R changeNotReaderChat(Integer toId) {
        try {
            if(userService.getUserById(toId)==null) return R.error("接收用户不存在");
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer fromUserId = (Integer) map.get("id");
            UpdateWrapper<ChatList> update = Wrappers.update();
            update.eq("from_user_id", toId).eq("to_user_id", fromUserId).set("is_Looked", 1);
            if (!this.update(update)) {
                return R.error("修改失败");
            }
            return R.success(null, "修改成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ChatList getChatListById(Integer id) {
        ChatList chatList = this.getById(id);
        return chatList;
    }

    @Override
    public R deleteChat(Integer id) {
        try {
            ChatList chatList = this.getById(id);
            if (chatList == null) return R.error("未找到该记录，删除失败");
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer fromUserId = (Integer) map.get("id");
            if(!fromUserId.equals(chatList.getFromUserId())) return R.error("不能删除他人发送的消息");

            //获取当前时间
            LocalDateTime now = LocalDateTime.now();
            //判断chatList.getPostdate()或当前时间是否超过5分钟，不是就删除，是就返回错误
            long minutesDifference = ChronoUnit.MINUTES.between(chatList.getPostdate(), now);
            if (minutesDifference <= 5) {
                this.removeById(id);
                return R.success(null, "删除成功");
            } else {
                return R.error("距离发送消息已超过5分钟，无法删除");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
